package pl.edu.mimuw.irs.core.global;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-07
 */
public class IDManager implements Serializable {
	
	private static final long serialVersionUID = 1190763315242810833L;
	
	// *** Static attributes
	
	private int lastId = 0;
	private Set<String> usedIds = new HashSet<String>();
	public synchronized String getPrefixedNewId(String prefix) {
		String newId;
		do {
			newId = prefix + lastId++;
		} while (getUsedIds().contains(newId));
		return newId;
	}
	public synchronized String getNewId() {
		return getPrefixedNewId("Gen");
	}
	public synchronized void setNewId(int newId) {
		this.lastId = newId;
	}
	public synchronized Set<String> getUsedIds() {
		if (usedIds == null) usedIds = new HashSet<String>();
		return usedIds;
	}
	public synchronized void setUsedIds(Set<String> usedIds) {
		this.usedIds = usedIds;
	}
	
	// *** Attributes
	
	// Unique identifier
	private String id;
	// Getters and setters
	public String getId() {
		if (id == null) id = getNewId();
		return id;
	}
	public void setId(String id) {
		if (id != null) {
			// XXX if (getUsedIds().contains(id)) throw new InternalException(Cause.GLOBAL_REPEATED_ID);
			this.id = id;
			getUsedIds().add(id);
		}
	}
	
	// *** Methods
	@Override
	public String toString() {
		return this.getClass().getSimpleName() + "(" + getId() + ")";
	}
	
	@Override
	protected void finalize() throws Throwable {
		getUsedIds().remove(getId());
		super.finalize();
	}
}
